package com.oj.common.security.service;

import cn.hutool.core.lang.UUID;
import com.oj.common.core.constants.CacheConstants;
import com.oj.common.core.constants.JwtConstants;
import com.oj.common.redis.service.RedisService;
import com.oj.common.core.domain.LoginUser;
import com.oj.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author bin
 * @Date 2025/4/14
 */
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, int value, String secret, String nickname, String headImage) {
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId.toString());
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        claims.put(JwtConstants.LOGIN_USER_HEADIMAGE, headImage);
        String token = JwtUtils.createToken(claims, secret);

        String key = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(value);
        loginUser.setNickName(nickname);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }


    public void extendToken(String token, String secret) {
        String redisTokenKey = getRedisTokenKey(token, secret);
        if (redisTokenKey == null) {
            return;
        }
        Long expire = redisService.getExpire(redisTokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(redisTokenKey, CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    public String getRedisTokenKey(String token, String secret) {
        Claims claims = null;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息 源码自己会校验签名信息
            if (claims == null) {
                log.error("解析token:{},出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token:{},出现异常:{}", token, e);
            return null;
        }
        String userKey = JwtUtils.getUserKey(claims); //获取jwt中的key
        return getTokenKey(userKey);
    }

    public Long getUserId(String token, String secret) {
        return Long.parseLong(JwtUtils.getUserId(JwtUtils.parseToken(token, secret)));
    }

    public String getTokenKey(String key) {
        return CacheConstants.LOGIN_TOKEN_KEY + key;
    }

    public LoginUser getLoginUser(String token, String secret) {
        String redisTokenKey = getRedisTokenKey(token, secret);
        return redisService.getCacheObject(redisTokenKey, LoginUser.class);
    }

    public void refreshLoginUser(String nickName, String headImage, String redisTokenKey) {
        LoginUser loginUser = redisService.getCacheObject(redisTokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(redisTokenKey, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
    }
}
